using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using IReaper.FileData;
using IReaper.Running;
using IReaper.Properties;

namespace IReaper.Statues
{
    public partial class PauseFileWork : CourseFileWorkBase
    {
        public PauseFileWork()
        {
            InitializeComponent();
        }

        public PauseFileWork(IContainer container)
        {
            container.Add(this);

            InitializeComponent();
        }

        protected override void OnDoWork(DoWorkEventArgs e)
        {
            Running.DownloadEngine.PauseDownloadEngine(false);
            CourseFileData cfd = null;
            int scanningPercentage = 0;
            int runningPercentage = 0;
            int savingPercentage = 0;
            //create a list to store running items
            List<CourseFileData> runninglist = new List<CourseFileData>();
            //loop one: check queued items
            for (int i = 0; i < this.Data.Count; i++)
            {
                cfd = this.Data[i];
                //check
                if (cfd == null)
                    continue;
                //stop queued items
                if (cfd.RunState == RunningStatue.RunQueued ||
                         cfd.RunState == RunningStatue.RunRequest)
                {
                    cfd.RunState = RunningStatue.Stopped;
                }
                //store running item
                else
                {
                    runninglist.Add(cfd);
                }
                scanningPercentage = (int)(i * 100 / this.Data.Count / 3);
                this.ReportProgress(scanningPercentage, Resources.Scanning + cfd.Owner.Headline);
            }

            //loop two: check running items
            for (int i = 0; i < runninglist.Count; i++)
            {
                cfd = runninglist[i];
                if (cfd.RunningWorker != null)
                {
                    cfd.RunningWorker.PauseDownload();
                    runningPercentage = (int)(i * 100 / runninglist.Count / 3) + scanningPercentage;
                    this.ReportProgress(runningPercentage, Resources.Stopping + cfd.Owner.Headline);
                }
            }
            //loop three:persistency the value
            for (int i = 0; i < this.Data.Count; i++)
            {
                cfd = this.Data[i];
                if (cfd == null)
                    continue;
                cfd.Storage.Flush();
                savingPercentage = (int)(i * 100 / this.Data.Count / 3) + runningPercentage;
                this.ReportProgress(savingPercentage, Resources.Saving + cfd.Owner.Headline);
            }
            Running.DownloadEngine.ResumeDownloadEngine();
        }
    }
}
